var fs = require("fs");
var path = require("path");
var crypto = require("crypto");
let JSZIP = require("jszip");
var config = require("./Config")
var param = config.inputparam;
var qudao = config.qudao;
var dir_des = "./hotupdata/"; //对比的目标文件
var dir_res = "./hotupdatatemp/"; //要拷贝的源文件

function delDir(path, endcallback) {
    let files = [];
    if (fs.existsSync(path)) {
        files = fs.readdirSync(path);
        files.forEach((file, index) => {
            let curPath = path + "/" + file;
            if (fs.statSync(curPath).isDirectory()) {
                delDir(curPath, null); //递归删除文件夹
            } else {
                fs.unlinkSync(curPath); //删除文件
            }
        });
        fs.rmdirSync(path);
        if (endcallback) {
            // console.log("删除完毕 执行删除后的回调")
            endcallback()
        }
    }
}

var checkDirectory = function (src, dst, callback, copyendcall) {
    fs.access(dst, fs.constants.F_OK, (err) => {
        if (err) {
            fs.mkdirSync(dst);
            callback(src, dst, copyendcall);
        } else {
            callback(src, dst, copyendcall);
        }
    });
};


var copydir = function (src, dst, copyendcall) {
    let paths = fs.readdirSync(src); //同步读取当前目录
    paths.forEach(function (path) {
        var _src = src + '/' + path;
        var _dst = dst + '/' + path;
        fs.stat(_src, function (err, stats) { //stats  该对象 包含文件属性
            if (err) throw err;
            if (stats.isFile()) { //如果是个文件则拷贝 
                let readable = fs.createReadStream(_src); //创建读取流
                let writable = fs.createWriteStream(_dst); //创建写入流
                readable.pipe(writable);
            } else if (stats.isDirectory()) { //是目录则 递归 
                checkDirectory(_src, _dst, copydir, null);
                return;
            }
        });
    });
    if (copyendcall) {
        copyendcall();
    }
}

if (param) {
    function mkdirsSync(dirname) {
        if (fs.existsSync(dirname)) {
            return true;
        } else {
            if (mkdirsSync(path.dirname(dirname))) {
                fs.mkdirSync(dirname);
                return true;
            }
        }
    }
    //比较project.manifest文件
    var hallflag = false;
    for (let i = 0; i < param.length; i++) {
        if (param[i].name == "hall") {
            if (hallflag == true) // hall 只比较一次
            {
                continue;
            }
            hallflag = true;
        }
        mkdirsSync(path.join(dir_des + qudao + param[i].name));
        mkdirsSync(path.join(dir_res + qudao + param[i].name));
        var manifestName_res = "";
        var manifestName_des = "";
        if (param[i].name == "hall") {
            manifestName_res = path.join(dir_res + qudao + param[i].name + "/" + "project.manifest")
            manifestName_versionres = path.join(dir_res + qudao + param[i].name + "/" + "version.manifest")
            manifestName_des = path.join(dir_des + qudao + param[i].name + "/" + "project.manifest")
        } else {
            manifestName_res = path.join(dir_res + qudao + param[i].name + "/" + param[i].name + "_project.manifest")
            manifestName_versionres = path.join(dir_res + qudao + param[i].name + "/" + param[i].name + "_version.manifest")
            manifestName_des = path.join(dir_des + qudao + param[i].name + "/" + param[i].name + "_project.manifest")
        }
        var existsflag = fs.existsSync(manifestName_des)
        if (existsflag) //文件存在   比较manifest文件
        {
            var resstr = fs.readFileSync(manifestName_res, "utf8");
            var desstr = fs.readFileSync(manifestName_des, "utf8");
            var resversionstr = fs.readFileSync(manifestName_versionres, "utf8");

            var resstrjson = JSON.parse(resstr)
            var desstrjson = JSON.parse(desstr)
            var resversionjson = JSON.parse(resversionstr)

            var needcopy = false;
            for (k in resstrjson.assets) {
                if (!desstrjson.assets[k]) //增加了资源 重新version  拷贝到目标目录中
                {
                    needcopy = true;
                    break;
                } else {
                    if ((resstrjson.assets[k].size != desstrjson.assets[k].size) || (resstrjson.assets[k].md5 != desstrjson.assets[k].md5)) {
                        needcopy = true;
                        break;
                    }
                }
            }
            var newversion = desstrjson.version;
            var desversion = desstrjson.version;
            var resversion = resstrjson.version;
            var reg = new RegExp(resversion, "g");
            if (!needcopy) //完全是一样的 不拷贝
            {
                console.log("文件完全一样，不需要更新  ", param[i].name, "路径是：", param[i].path)
            } else { //assets有差异重新version拷贝到目标目录中
                console.log("文件有差异，需要更新  ", param[i].name, "路径是：", param[i].path)
                var des = desversion.split(".")
                newversion = des[0] + "." + des[1] + "." + String(Number(des[2]) + 1)
            }
            //整理project.manifest文件
            resstrjson.packageUrl = resstrjson.packageUrl.replace(reg, newversion);
            resstrjson.remoteManifestUrl = resstrjson.remoteManifestUrl.replace(reg, newversion);
            resstrjson.remoteVersionUrl = resstrjson.remoteVersionUrl.replace(reg, newversion);
            resstrjson.version = newversion;
            //整理version.manifest文件
            resversionjson.packageUrl = resversionjson.packageUrl.replace(reg, newversion);
            resversionjson.remoteManifestUrl = resversionjson.remoteManifestUrl.replace(reg, newversion);
            resversionjson.remoteVersionUrl = resversionjson.remoteVersionUrl.replace(reg, newversion);
            resversionjson.version = newversion;
            //重写manifest文件
            fs.writeFileSync(manifestName_res, JSON.stringify(resstrjson), "utf-8");
            fs.writeFileSync(manifestName_versionres, JSON.stringify(resversionjson), "utf-8");
            //重命名文件夹
            var oldPath = path.join(dir_res + qudao + param[i].name + "/" + resversion)
            var newPath = path.join(dir_res + qudao + param[i].name + "/" + newversion)
            try {
                fs.renameSync(oldPath, newPath);
            } catch (e) {
                fs.renameSync(oldPath, newPath);
            }
            if (param[i].name == "hall") {
                console.log(" 158L 写入newversion.txt  ", newversion)
                fs.writeFileSync("./newversion.txt", newversion, "utf-8");
            }
        } else { //文件不存在  直接拷贝过去
            if (param[i].name == "hall") {
                var resversionstr = fs.readFileSync(manifestName_versionres, "utf8");
                var resversionjson = JSON.parse(resversionstr)
                var newversion = resversionjson.version;
                console.log(" 172L 写入newversion.txt  ", newversion)
                fs.writeFileSync("./newversion.txt", newversion, "utf-8");
            }
        }
    }
}